﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;

namespace WebMvc.App.Code.Extend.Yun
{
	public class ToUp
	{

		public static void CreateTable()
		{
			string databaseFileName = System.Environment.CurrentDirectory + @"\yun.db";
			SQLiteConnection.CreateFile(databaseFileName);
			string connStr = @"Data Source=" + System.Environment.CurrentDirectory + @"\yun.db;Initial Catalog=main;Integrated Security=True;Max Pool Size=10";
			string createSql = @"create table content (id integer primary key AUTOINCREMENT not null,module varchar(20),yun varchar(2), 
							domain varchar(200),fileType varchar(20),isSuccess tinyint(1),isDeleted tinyint(1),
							localUrl varchar(200),yunUrl varchar(200),keyStr varchar(200),file varchar(200),bucketName varchar(200),
							accessId varchar(200), accessKey varchar(200),sceretKey varchar(200));";
			using (SQLiteConnection conn = new SQLiteConnection(connStr))
			{
				conn.Open();
				SQLiteCommand comm = conn.CreateCommand();
				comm.CommandText = createSql;
				comm.CommandType = CommandType.Text;
				comm.ExecuteNonQuery();
			}
		}
		public static int Insert(string insertSql, params SQLiteParameter[] parameters)
		{
			string connStr = @"Data Source=" + System.Environment.CurrentDirectory + @"\yun.db;Initial Catalog=main;Integrated Security=True;Max Pool Size=10";
			//StringBuilder strSql = new StringBuilder();
			//strSql.Append("insert into content(");
			//strSql.Append("module,yun,domain,fileType,isSuccess,isDeleted,localUrl,yunUrl,keyStr,file,bucketName,accessId,accessKey,sceretKey)");//
			//strSql.Append(" values (");
			//strSql.Append("@module,@yun,@domain,@fileType,@isSuccess,@isDeleted,@localUrl,@yunUrl,@keyStr,@file,@bucketName,@accessId,@accessKey,@sceretKey)");//

			////
			//SQLiteParameter[] parameters = {
			//new SQLiteParameter("@module","module"),
			//new SQLiteParameter("@yun", "yun"),
			//new SQLiteParameter("@domain", "domain"),
			//new SQLiteParameter("@fileType","fileType"),
			//new SQLiteParameter("@isSuccess",true),
			//new SQLiteParameter("@isDeleted",false),
			//new SQLiteParameter("@localUrl","localUrl"),
			//new SQLiteParameter("@yunUrl","yunUrl"),
			//new SQLiteParameter("@keyStr","keyStr"),
			//new SQLiteParameter("@file","file"),
			//new SQLiteParameter("@bucketName","bucketName"),
			//new SQLiteParameter("@accessId","accessId"),
			//new SQLiteParameter("@accessKey","accessKey"),
			//new SQLiteParameter("@sceretKey","sceretKey")
			//							   };
			using (SQLiteConnection conn = new SQLiteConnection(connStr))
			{
				conn.Open();
				SQLiteCommand comm = conn.CreateCommand();
				comm.CommandText = insertSql;
				comm.Parameters.AddRange(parameters);
				comm.CommandType = CommandType.Text;
				return comm.ExecuteNonQuery();
			}

			//string sql = "INSERT INTO user2 VALUES(1,'a','b',1.0)";

			//int count;
			//using (DbConnection conn = new SQLiteConnection(connStr))
			//{
			//	conn.Open();
			//	DbCommand comm = conn.CreateCommand();
			//	comm.CommandText = "select * from content";
			//	comm.CommandType = CommandType.Text;
			//	count = Convert.ToInt32(comm.ExecuteScalar());
			//}
		}

		public static int Update(string updateSql, params SQLiteParameter[] parameters)
		{
			string connStr = @"Data Source=" + System.Environment.CurrentDirectory + @"\yun.db;Initial Catalog=main;Integrated Security=True;Max Pool Size=10";
			using(SQLiteConnection conn=new SQLiteConnection(connStr))
			{
				conn.Open();
				SQLiteCommand comm = conn.CreateCommand();
				comm.CommandText = updateSql;
				comm.Parameters.AddRange(parameters);
				comm.CommandType = CommandType.Text;
				return comm.ExecuteNonQuery();
			}
		}

		public static DataTable ExecuteTable(string sql,params SQLiteParameter[] parameters)
		{
			string connStr = @"Data Source=" + System.Environment.CurrentDirectory + @"\yun.db;Initial Catalog=main;Integrated Security=True;Max Pool Size=10";
			using(SQLiteConnection conn=new SQLiteConnection(connStr))
			{
				conn.Open();
				SQLiteCommand comm = conn.CreateCommand();
				comm.CommandText = sql;
				comm.Parameters.AddRange(parameters);
				comm.CommandType = CommandType.Text;
				SQLiteDataAdapter adapter = new SQLiteDataAdapter(comm);
				DataSet dSet=new DataSet();
				adapter.Fill(dSet);
				DataTable table = new DataTable();
				return dSet.Tables[0];
				
			}
		}
			

		public static bool UpToYun(string path,string accessKey, string sceretKey, string bucketName, string chooseYun, string accessId, string domain, string module)
		{
			string[] filePaths = Directory.GetDirectories(path);
			foreach (string filePath in filePaths)
			{
				string[] ffPath = Directory.GetDirectories(filePath);

				//string[] ffFiles = Directory.GetFiles(filePath);

				#region ffFiles.Length>0
				//if (ffFiles.Length > 0)
				//{
				//	foreach (string file in ffFiles)
				//	{
				//		count++;
				//		string fileName = Path.GetFileName(file);//11.css
				//		string strFileType = string.Empty;
				//		foreach (string preFloder in file.Substring(filePath.IndexOf(module + "\\")).Split('\\'))
				//		{
				//			strFileType = strFileType + "/" + preFloder;
				//		}
				//		//string fileType = filePath.Split('\\')[filePath.Split('\\').Length - 1];
				//		string key = strFileType.TrimStart('/');

				//		string keyGUID = "/" + Guid.NewGuid().ToString();

				//		bool isSuccess = false;
				//		string localUrl = "/" + key;
				//		string yunUrl = domain + "/" + key;
						

				//		if (chooseYun == "1")//阿里云
				//		{
				//			IUploadable yun = Base.GetYun(yunType.ALi);
				//			yun.Initial(bucketName, key, file, accessId, accessKey, "", "http://testcontent.oss-cn-hangzhou.aliyuncs.com");
				//			isSuccess = yun.Upload(bucketName, key, file, accessId, accessKey, "", "http://testcontent.oss-cn-hangzhou.aliyuncs.com", 2 * 1024 * 1024);
				//			//bool isSuccess = UpDownload.ResumablePutFile("testapp", key + keyGUID, file);
				//			if (isSuccess)
				//			{
				//				flag++;
				//				//则将此条记录的上传标识设置为1，
				//				OperateDataSuccess();
				//			}
				//			else if (!isSuccess)
				//			{
				//				yunUrl = "";
				//				//上传失败，也将此条记录记录到数据库中，-1
				//				OperateDataFalse();
				//			}
				//			else
				//			{
				//				//出现未知错误
				//			}

				//		}
				//		else if (chooseYun == "2")
				//		{
				//			IUploadable yun = Base.GetYun(yunType.QiNiu);
				//			yun.Initial("", "", "", "", accessKey, sceretKey, "");
				//			isSuccess = yun.Upload(bucketName, key + keyGUID, file, "", accessKey, sceretKey, "", 0);
				//			//bool isSuccess = UpDownload.ResumablePutFile("testapp", key + keyGUID, file);
				//			if (isSuccess)
				//			{	
				//				flag++;
				//				//则将此条记录的上传标识设置为1，
				//				yunUrl = yunUrl + keyGUID;

				//				OperateDataSuccess();
				//			}
				//			else if (!isSuccess)
				//			{
				//				//上传失败，也将此条记录记录到数据库中，-1
								
				//				yunUrl = "";
				//				OperateDataFalse();
				//			}
				//			else
				//			{
				//				//出现未知错误
				//			}

				//		}
				//		else
				//		{
				//			//有默认云或其他
				//		}
						
				//	}
				//}
				#endregion


				#region ffPath.Length <= 0

				if (ffPath.Length <= 0)
				{
					string[] files = Directory.GetFiles(filePath);
					foreach (string file in files)
					{						
						string fileName = Path.GetFileName(file);//11.css
						string strFileType = string.Empty;
						foreach (string preFloder in file.Substring(filePath.IndexOf(module + "\\")).Split('\\'))
						{
							strFileType = strFileType + "/" + preFloder;
						}
						//string fileType = filePath.Split('\\')[filePath.Split('\\').Length - 1];
						string key = strFileType.TrimStart('/');

						string keyGUID = "/" + Guid.NewGuid().ToString();

						bool isSuccess = false;
						string localUrl = "/" + key;
						string yunUrl = domain + "/" + key;
						

						#region 阿里云
						if (chooseYun == "1")//阿里云
						{
							DataTable table = ExecuteTable("select * from content where localUrl=@localUrl and yun=1", new SQLiteParameter("@localUrl", localUrl));
							IUploadable yun = Base.GetYun(yunType.ALi);
							yun.Initial(bucketName, key, file, accessId, accessKey, "");
							isSuccess = yun.Upload(bucketName, key, file, accessId, accessKey, "", 2 * 1024 * 1024);
							//bool isSuccess = UpDownload.ResumablePutFile("testapp", key + keyGUID, file);
							if (isSuccess)
							{								
								//则将此条记录的上传标识设置为1，
								if (table.Rows.Count <= 0)
								{
									Insert("insert into content(module,yun,domain,fileType,isSuccess,isDeleted,localUrl,yunUrl,keyStr,file,bucketName,accessId,accessKey,sceretKey) values (@module,@yun,@domain,@fileType,1,1,@localUrl,@yunUrl,@keyStr,@file,@bucketName,@accessId,@accessKey,@sceretKey)",
									new SQLiteParameter("@module", module), new SQLiteParameter("@yun", chooseYun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", strFileType), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl),
									new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey));
								}
								else
								{
									Update("update content set module=@module,yun=@chooseYun,domain=@domain,fileType=@strFileType,isSuccess=1,isDeleted=1,localUrl=@localUrl,yunUrl=@yunUrl,keyStr=@key,file=@file,bucketName=@bucketName,accessId=@accessId,accessKey=@accessKey,sceretKey=@sceretKey where id=@id",
									new SQLiteParameter("@module", module), new SQLiteParameter("@yun", chooseYun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", strFileType), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl), new SQLiteParameter("@id", Convert.ToInt32(table.Rows[0]["id"])),
									new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey));
								}


							}
							else if (!isSuccess)
							{
								//上传失败，也将此条记录记录到数据库中，-1								
								yunUrl = "";

								if (table.Rows.Count <= 0)
								{
									Insert("insert into content(module,yun,domain,fileType,isSuccess,isDeleted,localUrl,yunUrl,keyStr,file,bucketName,accessId,accessKey,sceretKey) values (@module,@yun,@domain,@fileType,-1,1,@localUrl,@yunUrl,@keyStr,@file,@bucketName,@accessId,@accessKey,@sceretKey)",
									new SQLiteParameter("@module", module), new SQLiteParameter("@yun", chooseYun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", strFileType), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl),
									new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey));
								}
								else
								{
									Update("update content set module=@module,yun=@chooseYun,domain=@domain,fileType=@strFileType,isSuccess=-1,isDeleted=1,localUrl=@localUrl,yunUrl=@yunUrl,keyStr=@key,file=@file,bucketName=@bucketName,accessId=@accessId,accessKey=@accessKey,sceretKey=@sceretKey where id=@id",
									new SQLiteParameter("@module", module), new SQLiteParameter("@yun", chooseYun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", strFileType), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl), new SQLiteParameter("@id", Convert.ToInt32(table.Rows[0]["id"])),
									new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey));
								}

							}
							else
							{
								//出现未知错误
							}

						}
						#endregion

						#region 七牛云
						else if (chooseYun == "2")
						{
							DataTable table = ExecuteTable("select * from content where localUrl=@localUrl and yun=2", new SQLiteParameter("@localUrl", localUrl));
							IUploadable yun = Base.GetYun(yunType.QiNiu);
							yun.Initial("", "", "", "", accessKey, sceretKey);
							isSuccess = yun.Upload(bucketName, key + keyGUID, file, "", accessKey, sceretKey, 0);
							//bool isSuccess = UpDownload.ResumablePutFile("testapp", key + keyGUID, file);
							if (isSuccess)
							{
								//则将此条记录的上传标识设置为1，
								yunUrl = yunUrl + keyGUID;
								if (table.Rows.Count <= 0)
								{
									Insert("insert into content(module,yun,domain,fileType,isSuccess,isDeleted,localUrl,yunUrl,keyStr,file,bucketName,accessId,accessKey,sceretKey) values (@module,@yun,@domain,@fileType,1,1,@localUrl,@yunUrl,@keyStr,@file,@bucketName,@accessId,@accessKey,@sceretKey)",
																	new SQLiteParameter("@module", module), new SQLiteParameter("@yun", chooseYun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", strFileType), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl),
																	new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey));
								}
								else
								{
									Update("update content set module=@module,yun=@chooseYun,domain=@domain,fileType=@strFileType,isSuccess=-1,isDeleted=1,localUrl=@localUrl,yunUrl=@yunUrl,keyStr=@key,file=@file,bucketName=@bucketName,accessId=@accessId,accessKey=@accessKey,sceretKey=@sceretKey where id=@id",
									new SQLiteParameter("@module", module), new SQLiteParameter("@yun", chooseYun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", strFileType), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl), new SQLiteParameter("@id", Convert.ToInt32(table.Rows[0]["id"])),
									new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey));
								}

							}
							else if (!isSuccess)
							{
								//上传失败，也将此条记录记录到数据库中，-1
								yunUrl = "";
								if (table.Rows.Count <= 0)
								{
									Insert("insert into content(module,yun,domain,fileType,isSuccess,isDeleted,localUrl,yunUrl,keyStr,file,bucketName,accessId,accessKey,sceretKey) values (@module,@yun,@domain,@fileType,-1,1,@localUrl,@yunUrl,@keyStr,@file,@bucketName,@accessId,@accessKey,@sceretKey)",
									new SQLiteParameter("@module", module), new SQLiteParameter("@yun", chooseYun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", strFileType), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl),
									new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey));
								}
								else
								{
									Update("update content set module=@module,yun=@chooseYun,domain=@domain,fileType=@strFileType,isSuccess=-1,isDeleted=1,localUrl=@localUrl,yunUrl=@yunUrl,keyStr=@key,file=@file,bucketName=@bucketName,accessId=@accessId,accessKey=@accessKey,sceretKey=@sceretKey where id=@id",
									new SQLiteParameter("@module", module), new SQLiteParameter("@yun", chooseYun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", strFileType), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl), new SQLiteParameter("@id", Convert.ToInt32(table.Rows[0]["id"])),
									new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey));
								}

							}
							else
							{
								//出现未知错误
							}

						}
						#endregion
						
						else
						{
							//有默认云或其他
						}
					}
				}
				#endregion

				else
				{
					UpToYun(filePath,accessKey, sceretKey, bucketName, chooseYun, accessId, domain, module);
				}

			}

			int c = ExecuteTable("select count(1) from content where isSuccess=-1").Rows.Count;
			if (c <=0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		public static DataTable ListYunContent()
		{
			return ExecuteTable("select * from content where isDeleted=1");
		}

		public static void ReUp(int id, string key, string module, string file, string filetype, string yun, string domain, string bucketName, string accessId, string accessKey, string sceretKey)
		{
			bool isSuccess = false;
			int flag = 1;
			string fileName = key.Split('/')[key.Split('/').Length - 1];

			if (yun == "1")//阿里云
			{
				IUploadable yuntype = Base.GetYun(yunType.ALi);
				yuntype.Initial(bucketName, key, file, accessId, accessKey, "");
				isSuccess = yuntype.Upload(bucketName, key, file, accessId, accessKey, "", 2 * 1024 * 1024);
				//bool isSuccess = UpDownload.ResumablePutFile("testapp", key + keyGUID, file);
				if (isSuccess)
				{
					flag++;
					//则将此条记录的上传标识设置为1，
					string localUrl = "/" + key;
					string yunUrl = domain + "/" + key;
					Update("update content set module=@module,yun=1,domain=@domain,fileType=@filetype,isSuccess=1,isDeleted=1,localUrl=@localUrl,yunUrl=@yunUrl,keyStr=@key,file=@file,bucketName=@bucketName,accessId=@accessId,accessKey=@accessKey,sceretKey=@sceretKey where id=@id",
						new SQLiteParameter("@module", module), new SQLiteParameter("@yun", yun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", filetype), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl),
						new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey),new SQLiteParameter("@id",id));
					
				}
				else if (!isSuccess)
				{
					//上传失败，也将此条记录记录到数据库中，-1
					string localUrl = "/" + key;
					string yunUrl = "";
					Update("update content set (module=@module,yun=1,domain=@domain,fileType=@filetype,isSuccess=-1,isDeleted=1,localUrl=@localUrl,keyStr=@key,file=@file,bucketName=@bucketName,accessId=@accessId,accessKey=@accessKey,sceretKey=@sceretKey where id=@id",
						new SQLiteParameter("@module", module), new SQLiteParameter("@yun", yun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", filetype), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl),
						new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey), new SQLiteParameter("@id", id));
					
				}
				else
				{
					//出现未知错误
				}

			}
			else if (yun == "2")
			{
				//七牛云
				IUploadable yuntype = Base.GetYun(yunType.QiNiu);
				yuntype.Initial("", "", "", "", accessKey, sceretKey);
				isSuccess = yuntype.Upload(bucketName, key, file, "", accessKey, sceretKey, 0);
				//bool isSuccess = UpDownload.ResumablePutFile("testapp", key + keyGUID, file);
				if (isSuccess)
				{
					flag++;
					//则将此条记录的上传标识设置为1，
					string localUrl = "/" + key;
					string yunUrl = domain + "/" + key;
					Update("update content set module=@module,yun=2,domain=@domain,fileType=@filetype,isSuccess=1,isDeleted=1,localUrl=@localUrl,yunUrl=@yunUrl,keyStr=@key,file=@file,bucketName=@bucketName,accessId=@accessId,accessKey=@accessKey,sceretKey=@sceretKey where id=@id",
						new SQLiteParameter("@module", module), new SQLiteParameter("@yun", yun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", filetype), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl),
						new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey), new SQLiteParameter("@id", id));
				}
				else if (!isSuccess)
				{
					//上传失败，也将此条记录记录到数据库中，-1
					string localUrl = "/" + key;
					string yunUrl = "";
					Update("update content set module=@module,yun=2,domain=@domain,fileType=@filetype,isSuccess=-1,isDeleted=1,localUrl=@localUrl,keyStr=@key,file=@file,bucketName=@bucketName,accessId=@accessId,accessKey=@accessKey,sceretKey=@sceretKey where id=@id",
						new SQLiteParameter("@module", module), new SQLiteParameter("@yun", yun), new SQLiteParameter("@domain", domain), new SQLiteParameter("@fileType", filetype), new SQLiteParameter("@localUrl", localUrl), new SQLiteParameter("@yunUrl", yunUrl),
						new SQLiteParameter("@keyStr", key), new SQLiteParameter("@file", file), new SQLiteParameter("@bucketName", bucketName), new SQLiteParameter("@accessId", accessId), new SQLiteParameter("@accessKey", accessKey), new SQLiteParameter("@sceretKey", sceretKey), new SQLiteParameter("@id", id));
				}
				else
				{
					//出现未知错误
				}
			}
		}
	}
}
